#include"threadPool.h"
#include<shadow.h>
#include "../tlv/tlv.h"
#include<errno.h>
#include<crypt.h>

int check(const char *username,const char *password){
    char error_str[1024];
    struct spwd *shadow_entry = getspnam(username);
    if (!shadow_entry) {
        strerror_r(errno,error_str,sizeof(error_str));
        fprintf(stderr,"getspnam:%s\n",error_str);
        return -1;
    }

    const char *stored_hash = shadow_entry->sp_pwdp;
    printf("Stored hash: %s\n", stored_hash);

    // 提取 prefix（salt + algorithm info）
    // 我们只取前三个 $ 分隔的部分
    char prefix[256] = {0};
    int dollar_count = 0;
    const char *p = stored_hash;
    const char *end = p;
    while (*end && dollar_count < 4) {
        if (*end == '$') {
            dollar_count++;
        }
        end++;
    }

    if (dollar_count < 4) {
        fprintf(stderr, "Invalid hash format.\n");
        return -1;
    }

    size_t len = end - stored_hash;
    strncpy(prefix, stored_hash, len);
    printf("Salt prefix for crypt: %s\n", prefix);

    // 进行加密
    struct crypt_data pwd_crypt_data;
    pwd_crypt_data.initialized='\0';
    char *computed_hash = crypt_r(password, prefix,&pwd_crypt_data);
    if (!computed_hash) {
        strerror_r(errno,error_str,sizeof(error_str));
        fprintf(stderr,"crypt:%s\n",error_str);
        return -1;
    }

    printf("Computed hash: %s\n", computed_hash);

    // 比较
    if (strcmp(computed_hash, stored_hash) == 0) {
        printf("Password match!\n");
        return 0;
    } else {
        printf("Password mismatch.\n");
        return -1;
    }
    return -1;
}
